﻿
#define DISABLE_POP3 // The POP3 function is not ready for now.

using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using UDS.Components;
using UDS.Entity;
using UDS.WebApp;
using UDS.Web.UI.Controls;

namespace UDS.SubModule.UnitiveDocument.Mail
{
    /// <summary>
    /// Index 的摘要说明。
    /// </summary>
    public partial class MailListPage : System.Web.UI.Page
    {
#if DISABLE_POP3
        protected const bool ShowExternalMail = false;
#else
        protected const bool ShowExternalMail = true;
#endif

        #region Properties
        protected bool SortAsc
        {
            get
            {
                object obj = ViewState["SortAsc"];
                if (obj == null)
                {
                    return false;
                }
                return (bool)obj;
            }
            set { ViewState["SortAsc"] = value; }
        }

        protected MailSortBy SortBy
        {
            get
            {
                object obj = ViewState["SortBy"];
                if (obj == null)
                {
                    return MailSortBy.Default;
                }
                return (MailSortBy)ViewState["SortBy"];
            }
            set { ViewState["SortBy"] = value; }
        }

        protected MailFolderType FolderType
        {
            get;
            private set;
        }

        protected int CurrentPageIndex
        {
            get
            {
                object obj = ViewState["PageIndex"];
                if (obj == null)
                {
                    return 0;
                }
                return (int)obj;
            }
            private set
            {
                ViewState["PageIndex"] = value;
            }
        }
        #endregion Properties

        protected override void OnInit(EventArgs e)
        {
            // Hook event handlers
            btnClear.Click += btnClear_Click;
            btnDelete.Click += btnDelete_Click;
#if !DISABLE_POP3
            btnBeginReceive.Click += btnBeginReceive_Click;
#endif

            FolderType = (MailFolderType)QSUtil.GetPositiveInt32("FolderType", (int)MailFolderType.Index);
            if (FolderType == MailFolderType.RecyleBin)
            {
                btnClear.Visible = true;
            }
#if !DISABLE_POP3
            else if (FolderType == MailFolderType.ExternalMail)
            {
                btnExtPopSetup.Visible = true;
                listExtMail.Visible = true;
                btnBeginReceive.Visible = true;
            }
#else
            if (FolderType == MailFolderType.ExternalMail)
            {
                FolderType = MailFolderType.Index;
            }
#endif

            base.OnInit(e);
        }

        protected override void OnLoad(EventArgs e)
        {
            if (!IsPostBack)
            {
                PopulateListView();
                BindGrid();
            }
            base.OnLoad(e);
        }

        public string GetRealNameStr(string Username)
        {
            if (Username != "")
                return UDS.Components.Staff.GetRealNameForStaffList(Username, 3);
            else
                return "";
        }

        #region 将数据排序
        /// <summary>
        /// 将信件按照指定字段进行排序
        /// </summary>
        protected void DataGrid_Sort(Object Src, DataGridSortCommandEventArgs E)
        {
            MailSortBy sortBy = (MailSortBy)Enum.Parse(typeof(MailSortBy), E.SortExpression, true);
            if (sortBy != SortBy)
            {
                SortBy = sortBy;
            }
            else
            {
                SortAsc = !SortAsc;
            }

            BindGrid();
        }
        #endregion

        #region 将邮件转移至指定信箱
        public void FolderListChange(object sender, System.EventArgs e)
        {
            bool sqlFlag = true;
            string sql = "";
            int FolderType = Int32.Parse(this.listFolderType.SelectedItem.Value); //设置转移目标
            MailClass mail = new MailClass();
            foreach (DataGridItem dgi in dgMailList.Items)
            {
                CheckBox cb = (CheckBox)(dgi.Cells[0].Controls[1]);
                if (cb.Checked == true)
                {
                    int i = dgi.ItemIndex;
                    string id = dgMailList.DataKeys[i].ToString();
                    if (sqlFlag)
                    {
                        sql += " MailID= " + id;
                        sqlFlag = false;
                    }
                    else
                    {
                        sql += " or";
                        sql += " MailID= " + id;
                    }
                }
            }
            //选择为空
            if (sql == String.Empty)
            {
                SiteContext.Current.AlertAndRedirect("请选择邮件", "Index.aspx?FolderType=" + (int)FolderType);
            }
            else
            {
                if (mail.MailRemove(FolderType, sql))
                {
                    SiteContext.Current.AlertAndRedirect("邮件移动成功!", "Index.aspx?FolderType=" + (int)FolderType);
                }
                else
                {
                    SiteContext.Current.Alert("邮件移动失败！");
                }
            }
            mail = null;
        }
        #endregion


        #region 数据绑定至DataGrid
        /// <summary>
        /// 将某用户的邮件取出绑定至DataGrid
        /// </summary>
        protected void BindGrid()
        {
            List<MailInfo> mails = UDSMail.GetMails(SiteContext.Current.UserName, FolderType);
            mails.Sort(new MailInfoComparer(SortBy, SortAsc));

            dgMailList.CurrentPageIndex = CurrentPageIndex;
            dgMailList.DataSource = mails;
            dgMailList.DataBind();

            //根据邮箱类别显示和隐藏列
            switch (FolderType)
            {
                case MailFolderType.Index:
                    dgMailList.Columns[3].Visible = false; //　隐藏收件人
                    dgMailList.Columns[4].Visible = false; //　隐藏所有收件人
                    break;

                case MailFolderType.Outbox:
                    dgMailList.Columns[2].Visible = false; //　隐藏发件人
                    dgMailList.Columns[3].Visible = false;  //　隐藏收件人
                    //dgMailList.Columns[4].Visible = true; //　隐藏所有收件人
                    break;

                case MailFolderType.RecyleBin:
                    dgMailList.Columns[2].Visible = true; //　显示发件人
                    dgMailList.Columns[3].Visible = false; //　隐藏收件人
                    dgMailList.Columns[4].Visible = false; //　隐藏所有收件人
                    break;

                case MailFolderType.ExternalMail:
                    dgMailList.Columns[4].Visible = false;  //　隐藏收件人
                    dgMailList.Columns[6].Visible = false; //　隐藏所属项目
                    break;
            }

            if (FolderType != MailFolderType.ExternalMail)
            {
                int numNew = 0;
                foreach (MailInfo m in mails)
                {
                    if (m.IsNew)
                    {
                        numNew++;
                    }
                }

                lblMsg.Text = mails.Count + "/<font color=\"red\">" + numNew + "</font>未读";
                lblMsg.Text += (!SortAsc) ? "&nbsp;&nbsp;" + Arrow.GetHtmlCode(ArrowDirection.Bottom) : "&nbsp;&nbsp;" + Arrow.GetHtmlCode(ArrowDirection.Top);
            }
            if (mails.Count > 0)
            {
                btnDelete.Visible = true;
            }
        }

        #endregion

        #region 翻页事件
        public void DataGrid_PageChanged(object sender, DataGridPageChangedEventArgs e)
        {
            dgMailList.CurrentPageIndex = e.NewPageIndex;
            CurrentPageIndex = dgMailList.CurrentPageIndex;

            BindGrid();
        }
        #endregion

        #region 初始化下拉列表框
        /// <summary>
        /// 对下拉列表进行初始化
        /// </summary>
        private void PopulateListView()
        {
            listFolderType.Items.Clear();
            listFolderType.Items.Add(new ListItem("放入邮件夹...", "0"));
            listFolderType.Items.Add(new ListItem("收件夹", ((int)MailFolderType.Index).ToString()));
            listFolderType.Items.Add(new ListItem("已经发送的邮件", ((int)MailFolderType.Outbox).ToString()));
            listFolderType.Items.Add(new ListItem("废件夹", ((int)MailFolderType.RecyleBin).ToString()));

            if (this.listExtMail.Visible)
            {
                this.listExtMail.DataTextField = "Title";
                this.listExtMail.DataValueField = "OrderID";
                this.listExtMail.DataSource = ExternalMail.ExtGetAvaSetting(SiteContext.Current.UserName);
                this.listExtMail.DataBind();
                this.listExtMail.Items.Insert(0, "全部外部邮箱");
                this.listExtMail.Items.FindByText("全部外部邮箱").Value = "0";
                this.listExtMail.SelectedIndex = 0;
            }
        }
        #endregion

        private void btnClear_Click(object sender, System.EventArgs e)
        {
            try
            {
                UDSMail.ClearFolder(SiteContext.Current.UserName, MailFolderType.RecyleBin);
                SiteContext.Current.AlertAndRedirect("邮件删除成功!", "Index.aspx?FolderType=" + (int)FolderType);
            }
            catch (Exception ex)
            {
                SiteContext.Current.AlertException("删除邮件失败", ex);
            }
        }

        private void btnDelete_Click(object sender, System.EventArgs e)
        {
            List<int> mailList = new List<int>();
            foreach (DataGridItem dgi in dgMailList.Items)
            {
                CheckBox cb = (CheckBox)(dgi.Cells[0].Controls[1]);
                if (cb.Checked == true)
                {
                    int i = dgi.ItemIndex;
                    string id = dgMailList.DataKeys[i].ToString();
                    mailList.Add(int.Parse(id));
                }
            }

            //选择为空
            if (mailList.Count == 0)
            {
                SiteContext.Current.AlertAndRedirect("请选择邮件!", "Index.aspx?FolderType=" + (int)FolderType);
            }
            else
            {

                if (FolderType == MailFolderType.RecyleBin)
                {
                    UDSMail.DeleteMail(mailList.ToArray(), true); // 彻底删除
                }
                else
                {
                    UDSMail.DeleteMail(mailList.ToArray(), false); // 丢到废件箱
                }

                SiteContext.Current.AlertAndRedirect("邮件删除成功!", "Index.aspx?FolderType=" + (int)FolderType);
            }
        }

#if !DISABLE_POP3
        private void btnBeginReceive_Click(object sender, System.EventArgs e)
        {
            MailClass mail = new MailClass();
            string Username = SiteContext.Current.UserName.ToString();
            int OrderID = Int32.Parse(this.listExtMail.SelectedItem.Value.ToString());
            try
            {
                mail.ReceiveMails(Username, OrderID);
                SiteContext.Current.Alert("接收完成!");
            }
            catch
            {
                SiteContext.Current.Alert("服务器正在忙碌中,请稍候再试");
            }
        }
#endif
    }
}
